package com.wzq.animal.back.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzq.animal.back.pojo.Permission;
import com.wzq.animal.back.service.PermissionService;
import com.wzq.animal.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    @GetMapping("/getPages/{currentPage}/{pageSize}")
    public Result getPages(@PathVariable("currentPage") int currentPage,
                           @PathVariable("pageSize") int pageSize,
                           @RequestParam("name") String name,
                           @RequestParam("comment") String comment) {
        Page<Permission> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Permission::getName,name)
                .like(Permission::getComment,comment);
        permissionService.page(page, queryWrapper);
        return Result.success(page);
    }

    @GetMapping("/findAll")
    public Result findAll(){
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(Permission::getPid);
        List<Permission> parentNode = permissionService.list(queryWrapper);
        for(Permission p : parentNode){
            queryWrapper.clear();
            queryWrapper.isNotNull(Permission::getPid).eq(Permission::getPid,p.getId());
            p.setChildren(permissionService.list(queryWrapper));
        }
        return Result.success(parentNode);
    }

    @PostMapping("/saveOrUpdatePermission")
    public Result saveOrUpdatePermission(@RequestBody Permission permission){
        permissionService.saveOrUpdate(permission);
        Integer id = permission.getId();
        if(StringUtils.isNotBlank(id.toString())){
            Permission updatedPermission = permissionService.getById(id);
            return Result.success(updatedPermission);
        }
        return Result.success();
    }

    @DeleteMapping("/delPermission/{id}")
    public Result delPermission(@PathVariable("id") int id) {
        permissionService.removeById(id);
        return Result.success();
    }

    @DeleteMapping("/delBatchPermission")
    public Result delBatch(@RequestBody List<Integer> ids) {
        permissionService.removeByIds(ids);
        return Result.success();
    }

}
